package com.learning.platform.controller;

import com.learning.platform.dto.ApiResponse;
import com.learning.platform.service.CaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 验证码控制器
 */
@RestController
@RequestMapping("/api/v1/captcha")
public class CaptchaController {
    
    @Autowired
    private CaptchaService captchaService;
    
    /**
     * 获取验证码key
     * @return 验证码key
     */
    @GetMapping("/key")
    public ResponseEntity<ApiResponse<Map<String, String>>> getCaptchaKey() {
        try {
            String key = captchaService.generateCaptcha();
            Map<String, String> data = new HashMap<>();
            data.put("key", key);
            return ResponseEntity.ok(ApiResponse.success(data));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(ApiResponse.error(500, "生成验证码失败"));
        }
    }
    
    /**
     * 获取验证码图片
     * @param key 验证码key
     * @return 验证码图片
     */
    @GetMapping("/image/{key}")
    public ResponseEntity<ApiResponse<Map<String, String>>> getCaptchaImage(@PathVariable String key) {
        try {
            String image = captchaService.generateCaptchaImage(key);
            Map<String, String> data = new HashMap<>();
            data.put("image", "data:image/png;base64," + image);
            return ResponseEntity.ok(ApiResponse.success(data));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(ApiResponse.error(500, "获取验证码图片失败: " + e.getMessage()));
        }
    }
    
    /**
     * 验证验证码
     * @param key 验证码key
     * @param code 用户输入的验证码
     * @return 验证结果
     */
    @PostMapping("/validate")
    public ResponseEntity<ApiResponse<Map<String, Object>>> validateCaptcha(
            @RequestParam String key,
            @RequestParam String code) {
        boolean isValid = captchaService.validateCaptcha(key, code);
        Map<String, Object> data = new HashMap<>();
        data.put("valid", isValid);
        
        if (isValid) {
            return ResponseEntity.ok(ApiResponse.success(data, "验证码正确"));
        } else {
            return ResponseEntity.status(400).body(ApiResponse.error(400, "验证码错误或已过期"));
        }
    }
}